package com.yang.qgg_demo.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yang.qgg_demo.common.R;
import com.yang.qgg_demo.entity.Bill;
import com.yang.qgg_demo.entity.Goods;
import com.yang.qgg_demo.entity.ShoppingCart;
import com.yang.qgg_demo.service.BillService;
import com.yang.qgg_demo.service.GoodsService;
import com.yang.qgg_demo.service.ShoppingCartService;
import com.yang.qgg_demo.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 购物车
 */
@Slf4j
@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private BillService billService;

    @Autowired
    private GoodsService goodsService;

    /**
     * 添加购物车
     */
    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart){
        log.info("购物车数据:{}",shoppingCart);

        //设置用户id，指定当前是哪个用户的购物车数据
        String currentUser =  TokenUtils.getUser();
        int currentId=1;
        if(currentUser != null){
            currentId = Integer.parseInt(currentUser);
            shoppingCart.setUserid(currentId);
        }
        else shoppingCart.setUserid(1);

        int goodsId = shoppingCart.getGoodsid();

        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserid,currentId);

        if(goodsId != 0){
            //添加到购物车的是菜品
            queryWrapper.eq(ShoppingCart::getGoodsid,goodsId);

        }else{
            //添加到购物车的是套餐
            queryWrapper.eq(ShoppingCart::getCategoryid,shoppingCart.getCategoryid());
        }

        //查询当前菜品或者套餐是否在购物车中
        ShoppingCart cartServiceOne = shoppingCartService.getOne(queryWrapper);

        if(cartServiceOne != null){
            //如果已经存在，就在原来数量基础上加一
            Integer number = cartServiceOne.getNumber();
            cartServiceOne.setNumber(number + 1);
            cartServiceOne.setMoney(shoppingCart.getPrice()*(number+1));
            shoppingCartService.updateById(cartServiceOne);
        }else{
            //如果不存在，则添加到购物车，数量默认就是一
            shoppingCart.setNumber(1);
            shoppingCart.setMoney(shoppingCart.getPrice());
            shoppingCartService.save(shoppingCart);
            cartServiceOne = shoppingCart;
        }

        return R.success(cartServiceOne);
    }

    /**
     * 查看购物车
     */
    @GetMapping("/page")
    public Page<ShoppingCart> findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize) {

        QueryWrapper<ShoppingCart> queryWrapper = new QueryWrapper<>();

        log.info(String.valueOf(shoppingCartService.page(new Page<>(pageNum, pageSize),queryWrapper)));
        return shoppingCartService.page(new Page<>(pageNum, pageSize),queryWrapper);
    }

    /**
     * 结账功能
     */
    @GetMapping("/checkout")
    public R<Bill> addBill(){

        System.out.println("------------------------------------------------jiezhang");
        List<ShoppingCart> list= shoppingCartService.getAllCartsWithMoneyGreaterThanZero();
        Bill bill = new Bill();
        Goods goods;
        Map<Integer,Integer> map=new HashMap<>();
        double money = 0;
        double profit = 0;
        bill.setUserid(list.get(0).getUserid());
        for(ShoppingCart shoppingCart : list){
            if(shoppingCart.getMoney()>0){
                money+=shoppingCart.getMoney();
                map.put(shoppingCart.getGoodsid(),shoppingCart.getNumber());
                goods=goodsService.getById(shoppingCart.getGoodsid());

                profit +=(goods.getPrice()-goods.getPerchaseprice())*shoppingCart.getNumber();
                goods.setStock(goods.getStock()-shoppingCart.getNumber());
                goods.setNumber(shoppingCart.getNumber()+goods.getNumber());
                goodsService.updateById(goods);
            }
        }
        String remark = map.toString();
        bill.setMoney(money);
        bill.setRemark(remark);
        bill.setProfit(profit);
        billService.save(bill);

        return R.success(bill);
    }

    /**
     * 清空购物车
     */
    @GetMapping("/clear")
    public void clearAllData() {
        shoppingCartService.clearAllData();
    }
}
